package rssmanager.servlets;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.*;

import rssmanager.service.*;


/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * Default constructor. 
	 */
	public LoginServlet() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		/*
		 * si l'utilisateur tape l'adresse de la servlet directement dans la barre d'adresse, il est renvoyé 
		 * sur la page d'accueil !
		 */
		response.sendRedirect("home.jsp");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		// on récupère les valeurs des deux champs du formulaire de la page de login
		ResultSet rs;
		String pseudo = request.getParameter("pseudo_connect");
		String mdp = request.getParameter("pass_connect");
		if(pseudo==null || pseudo.isEmpty() || mdp==null || mdp.isEmpty()) {
			response.sendRedirect("home.jsp");					
		} else {				
			try {
				PreparedStatement stmt = DBConnect.getConnection().prepareStatement("SELECT id_user, pseudo, email FROM Users WHERE pseudo = ? AND mot_de_passe = ?");
				stmt.setString(1, pseudo);
				stmt.setString(2, mdp);
				stmt.execute();
				rs = stmt.getResultSet();
				String id_user="";

				int rowCount = 0; 
				if(rs.next()) { 
					User currentUser = new User();
					currentUser.setLogin(rs.getString("pseudo"));
					currentUser.setPassword(mdp);
					currentUser.setId(rs.getString("id_user"));
					currentUser.setEmail(rs.getString("email"));
					
					//... et on le stocke dans la session courante.
					request.getSession().setAttribute("user", currentUser);
					
					// Enfin, on redirige les données vers la page content.jsp
					request.getRequestDispatcher("content.jsp").forward(request, response);
				} else {
					request.setAttribute("error", "Compte inexistant.");
					request.getRequestDispatcher("home.jsp").forward(request, response);
				}
	            rs.close();                                                               
	            stmt.close();                                                             
	            stmt = null;                                                              
			}
			catch(Exception e){
				System.out.println("Connection ratée: "+e);
				System.exit(-1);   
			}
		}
	}
}	
